<template>
  <div>
    <span class="times" v-if="countFlag">立即获取</span>
    <span class="times" v-else>剩余{{countNum}}S</span>
  </div>
</template>

<script>
export default {
  data() {
    return {
      countNum: 0, // 倒计时秒数
      countFlag: true
    }
  },
  created() {
    this.monitor()
    // this.countNum = this.countNum
    // this.countFlag = this.countFlag
  },
  methods: {
    monitor() {
      //监听关闭页面之后重新打开是否改继续倒计时
      let LocalDelay = this.getLocalDelay()
      console.log('监听关闭页面之后',LocalDelay)
      let timeLine = parseInt((new Date().getTime() - LocalDelay.time) / 1000)
      if (timeLine > LocalDelay.delay) {
        console.warn('倒计时过期')
      } else {
        this.countFlag = false
        this.countNum = LocalDelay.delay - timeLine
        let timer = setInterval(() => {
          if (this.countNum > 1) {
            this.countNum--
            this.setLocalDelay(this.countNum) //设置每一次还需倒计时
          } else {
            clearInterval(timer)
            this.countFlag = true
          }
        }, 1000)
      }
    },
    countDown(countFlag, countNum) {
      if (countFlag) {
        // debugger
        // if (this.countFlag) {
        // this.countFlag = false
        // this.countNum = 120
        this.countFlag = false
        this.countNum = countNum
        let timer = setInterval(() => {
          if (this.countNum > 1) {
            this.countNum--
            this.setLocalDelay(this.countNum)
          } else {
            clearInterval(timer)
            this.countFlag = true
          }
        }, 1000)
      } else {
        return false
      }
    },
    setLocalDelay(delay) {
      // location.href作为页面的唯一标识，可能一个项目中会有多个验证码。
      // console.log(delay, 'delay')
      localStorage.setItem('delay_' + location.href, delay)
      localStorage.setItem('time_' + location.href, new Date().getTime())
    },
    getLocalDelay() {
      let LocalDelay = {
        delay: localStorage.getItem('delay_' + location.href),
        time: localStorage.getItem('time_' + location.href)
      }
      return LocalDelay
    }
  }
}
</script>

<style>
</style>